<template>
  <div class="app-container">
    <!-- 头部导航栏 -->
    <HeaderNav 
      :active-menu="activeMenu" 
      @menu-select="handleMenuSelect" 
      @user-command="handleUserCommand" 
    />

    <!-- 主内容区域 -->
    <main class="main-content">
      <div class="page-container">
        <!-- 页面标题和操作区 -->
        <div class="page-header">
          <h1>我的简历</h1>
          <el-button type="primary" @click="openAddDialog">
            <el-icon><Plus /></el-icon>
            新增简历
          </el-button>
        </div>

        <!-- 简历列表 -->
        <el-card v-loading="loading" class="resume-list-card">
          <el-table :data="resumeList" border stripe>
            <el-table-column prop="resume_id" label="ID" width="100" />
            <el-table-column label="简历图片" width="200">
              <template #default="scope">
                <el-image 
                  :src="getFullImageUrl(scope.row.file_url)" 
                  :preview-src-list="[getFullImageUrl(scope.row.file_url)]"
                  style="width: 80px; height: 80px; object-fit: cover; cursor: pointer"
                  fit="cover"
                />
              </template>
            </el-table-column>
            <!-- 已删除“文件名称”列 -->
            <el-table-column prop="created_at" label="创建时间" width="300" />
            <el-table-column prop="updated_at" label="更新时间" width="300" />
            <el-table-column label="操作" width="230" align="center">
              <template #default="scope">
                <div class="operation-buttons">
                  <el-button 
                    size="small" 
                    type="text" 
                    @click="handleView(scope.row)"
                    class="op-btn"
                  >
                    查看
                  </el-button>
                  <el-button 
                    size="small" 
                    type="text" 
                    @click="openEditDialog(scope.row)"
                    class="op-btn"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    size="small" 
                    type="text" 
                    text-color="#ff4d4f"
                    @click="handleDelete(scope.row)"
                    class="op-btn"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination" v-if="pagination.total > 0">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.page"
              :page-sizes="[5, 10, 20]"
              :page-size="pagination.pageSize"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
          <div v-else class="no-data">暂无简历数据，请点击"新增简历"添加</div>
        </el-card>
      </div>
    </main>

    <!-- 新增/编辑简历弹窗 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="600px"
    >
      <el-form 
        :model="formData" 
        :rules="formRules" 
        ref="formRef"
        label-width="120px"
      >
        <el-form-item label="简历图片" prop="file_url">
          <!-- 图片上传组件 -->
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :limit="1"
            :file-list="fileList"
            list-type="picture-card"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                支持上传jpg/png格式图片，大小不超过5MB
              </div>
            </template>
          </el-upload>
          
          <!-- 预览区域 -->
          <el-image 
            v-if="formData.file_url"
            :src="formData.file_url" 
            style="width: 200px; height: auto; margin-top: 10px"
            fit="contain"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 查看简历弹窗 -->
    <el-dialog 
      title="简历详情" 
      v-model="viewDialogVisible" 
      width="800px"
    >
      <el-descriptions column="1" border>
        <el-descriptions-item label="ID">{{ currentResume.resume_id || '-' }}</el-descriptions-item>
        <el-descriptions-item label="简历图片">
          <el-image 
            v-if="currentResume.file_url"
            :src="currentResume.file_url" 
            :preview-src-list="[currentResume.file_url]"
            style="max-width: 100%; height: auto"
            fit="contain"
          />
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentResume.created_at || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ currentResume.updated_at || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 导入组件和API
import HeaderNav from '@/components/layout/HeaderNav.vue';
import resumeApi from '@/api/resume';
import { useUserStore } from '@/stores/user';

// 路由和状态管理
const router = useRouter();
const userStore = useUserStore();

// 导航相关状态
const activeMenu = ref('resume');

// 简历列表状态
const loading = ref(false);
const resumeList = ref([]);
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
  totalPages: 0
});

// 弹窗状态
const dialogVisible = ref(false);
const viewDialogVisible = ref(false);
const dialogTitle = ref('新增简历');
const currentResumeId = ref(null);
const currentResume = ref({});

// 上传相关配置
const uploadUrl = '/api/upload/resume'; // 图片上传接口地址
const uploadHeaders = reactive({
  // 确保Authorization头格式正确：Bearer + 空格 + token
  Authorization: `Bearer ${localStorage.getItem('token') || ''}` 
});
const fileList = ref([]); // 上传文件列表

// 表单数据和验证
const formData = reactive({
  file_url: '',
  visibility: 0
});
const formRules = reactive({
  file_url: [
    { required: true, message: '请上传简历图片', trigger: 'change' }
  ],
  visibility: [
    { required: true, message: '请选择可见性', trigger: 'change' }
  ]
});
const formRef = ref(null);

// 页面加载时初始化数据
onMounted(() => {
  if (!localStorage.getItem('token')) {
    router.push('/login');
    ElMessage.warning('请先登录');
    return;
  }
  fetchResumes();
});

// 获取简历列表数据
const fetchResumes = async () => {
  try {
    loading.value = true;
    const response = await resumeApi.getList({
      page: pagination.page,
      pageSize: pagination.pageSize
    });
    if (response.code === 0) {
      resumeList.value = response.data.list || [];
      pagination.total = response.data.pagination.total || 0;
      pagination.totalPages = response.data.pagination.totalPages || 0;
    } else {
      ElMessage.error(response.msg || '获取简历列表失败');
    }
  } catch (error) {
    console.error('获取简历列表出错:', error);
    ElMessage.error('获取简历列表失败，请刷新页面重试');
  } finally {
    loading.value = false;
  }
};

// 打开新增简历弹窗
const openAddDialog = () => {
  dialogTitle.value = '新增简历';
  currentResumeId.value = null;
  formData.file_url = '';
  formData.visibility = 0;
  fileList.value = []; // 清空上传列表
  dialogVisible.value = true;
};

// 打开编辑简历弹窗
const openEditDialog = (resume) => {
  dialogTitle.value = '编辑简历';
  currentResumeId.value = resume.resume_id;
  formData.file_url = resume.file_url;
  formData.visibility = resume.visibility;
  // 初始化文件列表
  fileList.value = resume.file_url ? [{ url: resume.file_url }] : [];
  dialogVisible.value = true;
};

// 上传成功处理
const handleUploadSuccess = (response) => {
  if (response.code === 0) {
    // 根据后端实际返回字段调整（可能是 url 而非 file_url）
    formData.file_url = response.data.file_url || response.data.url; 
    fileList.value = [{ url: getFullImageUrl(formData.file_url) }]; // 应用完整路径
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error(response.msg || '图片上传失败');
  }
};
const beforeUpload = (file) => {
  // 新增：检查Token是否存在
  if (!localStorage.getItem('token')) {
    ElMessage.error('请先登录');
    return false;
  }
  
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isJpgOrPng) {
    ElMessage.error('只能上传JPG/PNG格式的图片');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB');
    return false;
  }
  return true;
};

// 提交表单（新增/编辑）
const submitForm = async () => {
  try {
    await formRef.value.validate();
    
    if (currentResumeId.value) {
      // 编辑简历
      const response = await resumeApi.update(
        currentResumeId.value,
        formData
      );
      if (response.code === 0) {
        ElMessage.success('简历更新成功');
        dialogVisible.value = false;
        fetchResumes();
      } else {
        ElMessage.error(response.msg || '更新失败');
      }
    } else {
      // 新增简历
      const response = await resumeApi.create(formData);
      if (response.code === 0) {
        ElMessage.success('简历新增成功');
        dialogVisible.value = false;
        fetchResumes();
      } else {
        ElMessage.error(response.msg || '新增失败');
      }
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('表单提交出错:', error);
      ElMessage.error('操作失败，请重试');
    }
  }
};

// 查看简历详情
const handleView = async (resume) => {
  try {
    const response = await resumeApi.getById(resume.resume_id);
    if (response.code === 0) {
      currentResume.value = response.data;
      viewDialogVisible.value = true;
    } else {
      ElMessage.error(response.msg || '获取详情失败');
    }
  } catch (error) {
    console.error('获取简历详情出错:', error);
    ElMessage.error('获取详情失败');
  }
};

// 切换简历可见性
const toggleVisibility = async (resume) => {
  try {
    const newVisibility = resume.visibility === 1 ? 0 : 1;
    const response = await resumeApi.updateVisibility(resume.resume_id, newVisibility);
    
    if (response.code === 0) {
      ElMessage.success(`已${newVisibility === 1 ? '设为公开' : '设为私有'}`);
      fetchResumes();
    } else {
      ElMessage.error(response.msg || '更新失败');
    }
  } catch (error) {
    console.error('切换可见性出错:', error);
    ElMessage.error('操作失败');
  }
};

// 删除简历
const handleDelete = async (resume) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条简历吗？删除后不可恢复',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const response = await resumeApi.delete(resume.resume_id);
    if (response.code === 0) {
      ElMessage.success('删除成功');
      fetchResumes();
    } else {
      ElMessage.error(response.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除简历出错:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 分页事件处理
const handleSizeChange = (pageSize) => {
  pagination.pageSize = pageSize;
  pagination.page = 1;
  fetchResumes();
};
const handleCurrentChange = (page) => {
  pagination.page = page;
  fetchResumes();
};

// 导航菜单切换
const handleMenuSelect = (menuKey) => {
  activeMenu.value = menuKey;
  router.push({ name: menuKey.charAt(0).toUpperCase() + menuKey.slice(1) });
};

// 用户菜单操作
const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile');
      break;
    case 'resume':
      break;
    case 'settings':
      ElMessage.info('即将跳转到设置页面');
      router.push('/settings');
      break;
    case 'logout':
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      userStore.clearUserInfo();
      ElMessage.success('已退出登录');
      router.push('/login');
      break;
  }
};

const getFullImageUrl = (url) => {
  if (!url) return '';
  // 若为相对路径，拼接基础 URL
  if (url.startsWith('/') && !url.startsWith('//')) {
    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:7001';
    return `${baseUrl}${url}`;
  }
  return url;
};
</script>

<style scoped>
/* 原有样式保持不变 */
.app-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding: 20px 0;
}

.page-container {
  max-width: 1200px;
  width: 100%;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-header h1 {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.resume-list-card {
  width: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.pagination {
  margin-top: 16px;
  text-align: right;
}

.no-data {
  text-align: center;
  padding: 40px 0;
  color: #909399;
  font-size: 14px;
}

.file-link {
  color: #409eff;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
.file-link:hover {
  text-decoration: underline;
}

/* 新增上传组件样式 */
.upload-demo {
  margin-bottom: 15px;
}

@media (max-width: 768px) {
  .page-container {
    padding: 0 10px;
  }
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>